package cn.ac.aircas.system.service.impl;

import cn.ac.aircas.common.core.domain.entity.SysRole;
import cn.ac.aircas.common.core.domain.entity.SysUser;
import cn.ac.aircas.system.domain.SysRegion;
import cn.ac.aircas.system.domain.vo.CityVo;
import cn.ac.aircas.system.domain.vo.ProvinceCityVo;
import cn.ac.aircas.system.mapper.SysRegionMapper;
import cn.ac.aircas.system.mapper.SysRoleMapper;
import cn.ac.aircas.system.service.ISysRegionService;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import lombok.AllArgsConstructor;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import java.util.Map;

/**
 * @author li
 * @description 针对表【t_region】的数据库操作Service实现
 * @createDate 2025-04-07 14:58:30
 */
@Service
@AllArgsConstructor
public class SysRegionServiceImpl implements ISysRegionService {

    SqlSessionTemplate sqlSessionTemplate;

    @Autowired
    private SysRegionMapper sysRegionMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public List<SysRegion> selectRegionList(SysRegion sysRegion) {
        return sysRegionMapper.selectRegionList(sysRegion);
    }

    @Override
    public List<SysRegion> getRegionDistrict(SysRegion sysRegion) {
        return sysRegionMapper.getRegionDistrict(sysRegion);
    }

    @Override
    public List<CityVo> getRegionDistrictByCityName(String cityName) {
        return sysRegionMapper.getRegionDistrictByCityName(cityName);
    }

    @Override
    public List<Map> getDistrictBoundaryByCityName(String cityName, String districtName) {
        return sysRegionMapper.getDistrictBoundaryByCityName(cityName, districtName);
    }

    @Override
    public boolean importRegion(MultipartFile file) {
        try (Reader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
            CsvToBean<SysRegion> csvToBean = new CsvToBeanBuilder<SysRegion>(reader)
                    .withType(SysRegion.class)
                    .withIgnoreLeadingWhiteSpace(true)
                    .withThrowExceptions(false)
                    .build();
            List<SysRegion> sysRegions = csvToBean.parse();

            insertBatches(sysRegions);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return true;
    }

    @Override
    public List<ProvinceCityVo> getCityList(String status) {
        return sysRegionMapper.getCityList(status);
    }

    @Override
    public int updateRegion(SysRegion sysRegion) {
        return sysRegionMapper.updateRegion(sysRegion);
    }

    @Override
    public List<SysRegion> selectRegionList(SysRegion region, Long userId) {
        List<SysRegion> regionList = null;
        // 管理员显示所有菜单信息
        if (SysUser.isAdmin(userId)) {
            regionList = sysRegionMapper.selectRegionList(region);
        } else {
            region.getParams().put("userId", userId);
            regionList = sysRegionMapper.selectRegionListByUserId(region);
        }
        return regionList;
    }

    @Override
    public List<SysRegion> selectRegionList(Long userId) {
        return selectRegionList(new SysRegion(), userId);
    }

    @Override
    public List<Integer> selectRegionListByRoleId(Long roleId) {
        SysRole role = sysRoleMapper.selectRoleById(roleId);
        return sysRegionMapper.selectRegionListByRoleId(roleId, role.isMenuCheckStrictly());
    }


    public void insertBatches(List<SysRegion> bizLabels) {
        SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        try {
            SysRegionMapper mapper = session.getMapper(SysRegionMapper.class);
            for (int i = 0; i < bizLabels.size(); i++) {
                mapper.insert(bizLabels.get(i));

                if (i % 400 == 0 || i == bizLabels.size() - 1) {
                    session.commit();
                    session.clearCache();
                }
            }
        } catch (Exception e) {
            session.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}




